package com.springboot.springbootapi.service;


import com.springboot.springbootapi.model.User;
import com.springboot.springbootapi.repository.UserRepository;
import com.springboot.springbootapi.web.vm.UserVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    @Transactional
    public User addUser(UserVM userVM){
        //将userVM转换成user
        User user =new User(userVM);
        userRepository.save(user);
        return user;
    }
    @Transactional
    public void deleteUser(Integer id){
        userRepository.deleteById(id);
    }

    @Transactional
    public User updateUser(Integer id,UserVM userVM){
        User user = userRepository.getOne(id);
        user.setName(userVM.getName());
        user.setAge(userVM.getAge());
        user.setMobile(userVM.getMobile());
        userRepository.save(user);
        return user;
    }
}
